<template>
 <div class="p-2">
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined" v-if="mainId!=''" v-auth="'contracts:contracts:add'"> 新增</a-button>
        <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onExportXls" v-if="mainId!=''"> 导出</a-button>
        <j-upload-button  type="primary" preIcon="ant-design:import-outlined" @click="onImportXls" v-if="mainId!=''">导入</j-upload-button>
        <a-button type="primary" @click="handleCreateTeam" preIcon="ant-design:team-outlined" :disabled="selectedRowKeys.length !== 1" v-if="mainId!=''" v-auth="'teams:teams:createTeam'">创建团队</a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button v-auth="'contracts:contracts:deleteBatch'">批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
      </template>
    </BasicTable>

    <ContractDetailInfoModal ref="registerModal" @success="handleSuccess"/>

    <!-- 创建团队弹框 -->
    <a-modal
      v-model:open="createTeamModalVisible"
      title="创建团队"
      @ok="handleCreateTeamConfirm"
      @cancel="handleCreateTeamCancel"
      :confirmLoading="createTeamLoading"
    >
      <a-form :model="teamForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="团队名称" name="teamName" :rules="[{ required: true, message: '请输入团队名称' }]">
          <a-input v-model:value="teamForm.teamName" placeholder="请输入团队名称" />
        </a-form-item>
      </a-form>
    </a-modal>
   </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, unref, inject, watch } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage'
  import ContractDetailInfoModal from './components/ContractDetailInfoModal.vue'
  import { contractDetailInfoColumns } from './Contracts.data';
  import { contractDetailInfoList, contractDetailInfoDelete, contractDetailInfoDeleteBatch, contractDetailInfoExportXlsUrl, contractDetailInfoImportUrl, createTeam } from './Contracts.api';
  import { isEmpty } from "/@/utils/is";
  import { useMessage } from '/@/hooks/web/useMessage';
  import { downloadFile } from '/@/utils/common/renderUtils';
  
  const toggleSearchStatus = ref<boolean>(false);
  //接收主表id
  const mainId = inject('mainId') || '';
  //提示弹窗
  const $message = useMessage()
  const queryParam = {};

  // 创建团队弹框相关
  const createTeamModalVisible = ref<boolean>(false);
  const createTeamLoading = ref<boolean>(false);
  const teamForm = reactive({
    teamName: ''
  });
  const selectedRecordForTeam = ref<any>(null);
  // 列表页面公共参数、方法
  const { prefixCls, tableContext, onImportXls, onExportXls } = useListPage({
    tableProps: {
      api: contractDetailInfoList,
      columns: contractDetailInfoColumns,
      canResize: false,
      useSearchForm: false,
      actionColumn: {
        width: 180,
        fixed:'right'
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: '合同明细',
      url: contractDetailInfoExportXlsUrl,
      params: {
        'contractNumber': mainId
      }
    },
    importConfig: {
      url: ()=>{
        return contractDetailInfoImportUrl + '/' + unref(mainId)
      }
    }
  });

  //注册table数据
  const [registerTable, { reload}, { rowSelection, selectedRowKeys, selectedRows }] = tableContext;
  const registerModal = ref();
  const formRef = ref();
  const labelCol = reactive({
    xs:24,
    sm:4,
    xl:6,
    xxl:4
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });
  
  /**
   * 新增事件
   */
  function handleAdd() {
    if (isEmpty(unref(mainId))) {
  
        return;
    }
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }

  /**
   * 编辑事件
   */
  async function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }

  /**
   * 详情事件
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }
  
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await contractDetailInfoDelete({id: record.id}, handleSuccess);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await contractDetailInfoDeleteBatch({ids: selectedRowKeys.value}, handleSuccess);
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        auth: 'contracts:contracts:edit'
      },
    ]
  }
  
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record){
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
        },
        auth: 'contracts:contracts:delete'
      },
    ];
  }
  
  /**
   * 创建团队 - 显示弹框
   */
  function handleCreateTeam() {
    if (selectedRowKeys.value.length !== 1) {

      return;
    }

    // 获取选中的行数据并保存
    selectedRecordForTeam.value = selectedRows.value[0];
    console.log('选中的记录:', selectedRecordForTeam.value);

    // 重置表单并显示弹框
    teamForm.teamName = '';
    createTeamModalVisible.value = true;
  }

  /**
   * 创建团队弹框 - 确认
   */
  async function handleCreateTeamConfirm() {
    if (!teamForm.teamName.trim()) {

      return;
    }

    try {
      createTeamLoading.value = true;

      // 组合数据：选中的记录 + 团队名称，映射到团队表字段
      const requestData = {
        teamName: teamForm.teamName.trim(),
        itemName: selectedRecordForTeam.value.itemName,
        contractDetailInfoId: selectedRecordForTeam.value.id,
        // 可以添加其他需要的字段
        productType: selectedRecordForTeam.value.productType,
        productContent: selectedRecordForTeam.value.productContent,
        amount: selectedRecordForTeam.value.amount,
        contractNumber: selectedRecordForTeam.value.contractNumber,
      };

      console.log('提交的数据:', requestData);

      // 调用创建团队接口
      const response = await createTeam(requestData);

      if (response) {
        createTeamModalVisible.value = false;
        // 刷新表格
        reload();
      } else {

      }
    } catch (error) {
      console.error('创建团队失败:', error);
    } finally {
      createTeamLoading.value = false;
    }
  }

  /**
   * 创建团队弹框 - 取消
   */
  function handleCreateTeamCancel() {
    createTeamModalVisible.value = false;
    teamForm.teamName = '';
    selectedRecordForTeam.value = null;
  }

  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }

  watch(mainId, () => {
    queryParam['contractNumber'] = unref(mainId);
    reload();
  });
</script>
<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
  }
</style>
